package com.codebyorder.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.codebyorder.entity.User;
import com.codebyorder.exception.BusinessException;
import com.codebyorder.exception.BusinessExceptionCode;
import com.codebyorder.mapper.UserMapper;
import com.codebyorder.req.UserLoginReq;
import com.codebyorder.req.UserQueryReq;
import com.codebyorder.req.UserResetPasswordReq;
import com.codebyorder.req.UserSaveReq;
import com.codebyorder.resp.CommonResp;
import com.codebyorder.resp.PageResp;
import com.codebyorder.resp.UserLoginResp;
import com.codebyorder.resp.UserQueryResp;
import com.codebyorder.service.UserService;
import com.codebyorder.util.CopyUtil;
import com.codebyorder.util.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserMapper userMapper;
    @Resource
    private UserService userService;
    @Resource
    private RedisTemplate<Object,Object> redisTemplate;
    @Resource
    private SnowFlake snowFlake;

    private static final Logger LOG = LoggerFactory.getLogger(UserController.class);

    @GetMapping("/list")
    public CommonResp<PageResp<UserQueryResp>> list(@Valid UserQueryReq userQueryReq) {
        CommonResp<PageResp<UserQueryResp>> resp = new CommonResp<>();
        resp.setContent(userService.userToResp(userQueryReq));
        return resp;
    }

    @GetMapping("/all")
    public List<UserQueryResp> all(Long category2id) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category2_id",category2id);
        List<User> users = userMapper.selectList(queryWrapper);
        return CopyUtil.copyList(users, UserQueryResp.class);
    }

    @PostMapping("/save")
    public CommonResp<Object> save(@Valid @RequestBody UserSaveReq userSaveReq) {
        userSaveReq.setPassword(DigestUtils.md5DigestAsHex(userSaveReq.getPassword().getBytes()));
        User user = CopyUtil.copy(userSaveReq, User.class);
        if (user.getId() == null) {
            User users = userMapper.selectByLoginName(user.getLoginName());
            if (users == null) {
                userMapper.insert(user);
            }else {
                throw new BusinessException(BusinessExceptionCode.USER_LOGIN_NAME_EXIST);
            }
        } else {
            user.setLoginName(null);
            user.setPassword(null);
            userMapper.updateById(user);
        }
        return new CommonResp<>();
    }

    @DeleteMapping("/delete/{id}")
    public CommonResp<Object> delete(@PathVariable Long id) {
        userMapper.deleteById(id);
        return new CommonResp<>();
    }

    @PostMapping("/resetPassword")
    public CommonResp<Object> resetPassword(@Valid @RequestBody UserResetPasswordReq userResetPasswordReq) {
        userResetPasswordReq.setPassword(DigestUtils.md5DigestAsHex(userResetPasswordReq.getPassword().getBytes()));
        User user = CopyUtil.copy(userResetPasswordReq, User.class);
        userMapper.updateById(user);
        return new CommonResp<>();
    }
    @PostMapping("/login")
    public CommonResp<UserLoginResp> login(@Valid @RequestBody UserLoginReq userLoginReq) {
        userLoginReq.setPassword(DigestUtils.md5DigestAsHex(userLoginReq.getPassword().getBytes()));
        CommonResp<UserLoginResp> resp = new CommonResp<>();
        UserLoginResp userLoginResp=userService.login(userLoginReq);

        Long token = snowFlake.nextId();
        LOG.info("生成单点登录token：{}，并放入redis中", token);
        userLoginResp.setToken(token.toString());
        redisTemplate.opsForValue().set(token.toString(), JSONObject.toJSONString(userLoginResp),3600*24, TimeUnit.SECONDS);
        resp.setContent(userLoginResp);
        return resp;
    }

    @GetMapping("/logout/{token}")
    public CommonResp<Object> logout(@PathVariable String token) {
        redisTemplate.delete(token);
        LOG.info("从redis中删除token:{}",token);
        return new CommonResp<>();
    }

}
